package com.bigfans.userservice.api;

import com.bigfans.Constants;
import com.bigfans.framework.CurrentUser;
import com.bigfans.framework.CurrentUserFactory;
import com.bigfans.framework.exception.UserExistsException;
import com.bigfans.framework.exception.UserUnAuthorizedException;
import com.bigfans.framework.kafka.KafkaTemplate;
import com.bigfans.framework.utils.StringHelper;
import com.bigfans.framework.web.BaseController;
import com.bigfans.framework.web.RestResponse;
import com.bigfans.model.event.notification.RequestVCodeEvent;
import com.bigfans.userservice.api.form.UserLoginForm;
import com.bigfans.userservice.api.form.UserRegisterForm;
import com.bigfans.userservice.model.User;
import com.bigfans.userservice.service.UserService;
import com.bigfans.userservice.service.impl.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserApi extends BaseController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserService userService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    private Integer tokenPeriod = 60 * 60 * 24 * 7;

    /**
     * 执行登录请求
     *
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public RestResponse login(@RequestBody UserLoginForm user) throws Exception {
        User loginUser = userService.login(user.getAccount(), user.getPassword());
        if (loginUser == null) {
            throw new UserUnAuthorizedException();
        }
        CurrentUser currentUser = this.createCurrentUser(loginUser);
        String token = CurrentUserFactory.createToken(currentUser, Constants.TOKEN.JWT_SECURITY_KEY);
        Map<String, Object> data = new HashMap<>();
        data.put("account", currentUser.getAccount());
        data.put("token", token);
        data.put("tokenPeriod", currentUser.getPeriod()); // 保存7天
        return RestResponse.ok(data);
    }

    @RequestMapping(value = "/validateMobile", method = RequestMethod.POST)
    public RestResponse validateMobile(@RequestParam(name = "mobile") String mobile) throws Exception {
        boolean accountExist = userService.accountExist(mobile);
        return RestResponse.ok(accountExist);
    }

    @RequestMapping(value = "/requestVCode", method = RequestMethod.POST)
    public RestResponse sendVerificationCode(@RequestParam(name = "mobile") String mobile) {
        assert StringHelper.isNotEmpty(mobile);
        String code = StringHelper.createNumCode(6);
        kafkaTemplate.send(new RequestVCodeEvent(mobile, code));
        redisService.setVerificationCode(mobile, code);
        return RestResponse.ok();
    }

    /**
     * 执行退出请求
     *
     * @return RestResponse
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public RestResponse logout() {
//        getRequest().getSession().invalidate();
//        Cookie userCookie = CookieHolder.get(Constants.TOKEN.KEY_NAME);
//        if(userCookie != null){
//            userCookie.setMaxAge(0);
//            userCookie.setPath("/");
//        }
        return RestResponse.ok();
    }

    /**
     * 执行注册请求
     *
     * @param registerForm
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public RestResponse register(@RequestBody UserRegisterForm registerForm) throws Exception {

        String verificationCode = redisService.getVerificationCode(registerForm.getMobile());
        // 检测验证码
//        if (!registerForm.getVerificationCode().equals(verificationCode)) {
//            return RestResponse.error(ResponseStatus.CODE_INCORRECT, "");
//        }
        User user = new User();
        user.setMobile(registerForm.getMobile());
        user.setAccount(registerForm.getMobile());
        user.setPassword(registerForm.getPassword());
        // 判断用户是否存在
        if (userService.exist(user)) {
            throw new UserExistsException();
        }
        userService.regist(user);
        CurrentUser currentUser = this.createCurrentUser(user);
        String token = CurrentUserFactory.createToken(currentUser, Constants.TOKEN.JWT_SECURITY_KEY);
        Map<String, Object> data = new HashMap<>();
        data.put("account", currentUser.getAccount());
        data.put("token", token);
        data.put("tokenPeriod", currentUser.getPeriod()); // 保存7天
        return RestResponse.ok(data);
    }

    private CurrentUser createCurrentUser(User user) {
        CurrentUser currentUser = new CurrentUser();
        currentUser.setAccount(user.getAccount());
        currentUser.setLoginTime(new Date());
        currentUser.setPeriod(tokenPeriod);
        currentUser.setType(CurrentUser.TYPE.LOGIN_USER);
        currentUser.setUid(user.getId());
        return currentUser;
    }
}
